<?php

namespace app\api\controller;


use app\admin\model\Config;
use app\common\model\Category;
use app\common\model\Tags;
use think\facade\Db;
use Throwable;
use think\Response;
use app\common\library\Upload;
use app\common\controller\Frontend;

#[Apidoc\Title("公共部分")]
class Ajax extends Frontend
{
    protected array $noNeedLogin = ['area', 'buildSuffixSvg', 'tabnameinfo', 'querydict'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function tabnameinfo()
    {
        $table_name = $this->request->param('table_name', 'ba_houses');
        $sql = "SELECT COLUMN_NAME,COLUMN_COMMENT FROM `information_schema`.`columns`
WHERE `table_name` = '" . $table_name . "'";
        Db::execute($sql);
        return $this->success('', Db::ex($sql));
    }

    #[
        Apidoc\Title("上传文件图片"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/ajax/upload"),
        Apidoc\Param(name: "file", type: "string", require: true, desc: "上传文件", mock: ""),
        Apidoc\Returned("file", type: "array", desc: "上传文件信息"),
    ]
    public function upload(): void
    {
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload(null, 0, $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    #[
        Apidoc\Title("首页搜索参数字典"),
        Apidoc\Tag("sources"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/ajax/querydict"),
        Apidoc\Returned("sources", type: "array", desc: "房源类型"),
        Apidoc\Returned("hangye", type: "array", desc: "行业"),
    ]
    public function querydict()
    {
        $sources = (new Category())->where(['status' => 1])
            ->order('weigh desc')
            ->column("id,name");
        $map = [
            ['status', '=', 1],
            ['pid', '=', 0],
            ['type', 'in', ['hangye', 'zhoubian', 'qita', 'wuye']]
        ];
        $tags = (new Tags())->where($map)
            ->cache(true)
            ->order('weigh desc')
            ->column('id,string as name,image,type');
        $hangye = [];
        $zhoubian = [];
        $qita = [];
        $wuye = [];

        $custom_fields = [
            ['field' => 'category_ids', 'name' => '房源类型']
            , ['field' => 'industry', 'name' => '行业']
            , ['field' => 'acreage', 'name' => '面积']
            , ['field' => 'rent_money', 'name' => '租金']
            , ['field' => 'city', 'name' => '城市选择'],
            ['field' => 'address', 'name' => '详情地址']
            , ['field' => 'image', 'name' => '主图（列表）']
            , ['field' => 'images', 'name' => '图册']
            //,['field' => 'name', 'name' => '房源公告标题']
            , ['field' => 'introduction', 'name' => '房源详情']
            , ['field' => 'has_bounty', 'name' => '是否悬赏']
            , ['field' => 'reward', 'name' => '悬赏金额']
            , ['field' => 'user_id', 'name' => '发布人']
        ];
        $filed_config = (new Config())->where(['id' => 17])->find();
        $checked_fields = json_decode($filed_config['value'], true);
        $checked_fields = $checked_fields ? $checked_fields : [];
        //$this->success('自定义配置字段', ['custom_fields' => $custom_fields, 'checked_fields' => $checked_fields]);
        foreach ($tags as $tag) {
            if ($tag['type'] == 'hangye') {
                $tag['children'] = (new Tags())->where('pid', $tag['id'])->field('id,string as name,image,type')->cache(true)->select();
                $hangye[] = $tag;
            } else if ($tag['type'] == 'zhoubian') {
                $zhoubian[] = $tag;
            } else if ($tag['type'] == 'qita') {
                $qita[] = $tag;
            } else if ($tag['type'] == 'wuye') {
                $wuye[] = $tag;
            }
        }
        $dict_arr = [
            'sources' => $sources,
            'hangye' => $hangye,
            'qita' => $qita,
            'wuye' => $wuye,
            'hourse_filed' => $checked_fields,
            'custom_fields' => $custom_fields
        ];
        $this->success('', $dict_arr);
    }

    #[
        Apidoc\Title("导入房源模板"),
        Apidoc\Tag("sources"),
        Apidoc\Method("GET"),
        Apidoc\Url("/api/ajax/gettemplate"),
        Apidoc\Returned("hourse_template", type: "string", desc: "房源导入模板"),
        Apidoc\Returned("findstore_template", type: "string", desc: "找房导入模板"),
    ]
    public function gettemplate()
    {
        $this->success('导入文件模板',
            [
                'hourse_template' => request()->domain() . '/templates/hourse_template.xlsx',
                'findstore_template' => request()->domain() . '/templates/findstore_template.xlsx'
            ]);
    }

    /**
     * 省份地区数据
     * @throws Throwable
     */
    #[
        Apidoc\Title("地区"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("GET"),
        Apidoc\Url("/api/ajax/area"),
        Apidoc\Query(name: "city", type: "number", require: false, desc: "昆明市 为空获取云南省分下级数据", mock: "2651"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function area(): void
    {
        $province = request()->param('province', '2650');
        $city = request()->param('city', '');
        $where = ['pid' => 0, 'level' => 1];
        if ($province !== '') {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== '') {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }

        $list = Db::name('area')
            ->where($where)
            ->field('id as value,name as label')
            ->select()
            ->toArray();
        $this->success('获取成功', $list);
    }

    public function buildSuffixSvg(): Response
    {
        $suffix = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }
}
